﻿using FluentValidation;
using Nuclear.Models.DtoModels;
using Errors = Nuclear.Models.DtoModels.Errors;

namespace Nuclear.Validations;
using static Errors;

public static class ValidatorExtensions
{
    public static void SetApiKey(string apiKey)
    {
        ApiKey = apiKey;
    }

    private static string ApiKey { get; set; } = "";

    public static async Task<TResponse?> ValidateRequestAsync<TRequest, TResponse>(
        this IValidator<TRequest> validator, 
        string apiKey,
        TRequest request,
        CancellationToken token = default
    )
        where TResponse: BaseResponseDto, new()
    {
        if (apiKey != ApiKey)
            return Unauthorized<TResponse>();

        var result = await validator.ValidateAsync(request, token);
        if (result.IsValid) return default;
        var errors = result.Errors;
        var message = errors.Aggregate("",
            (e, error) => $"{e}{Environment.NewLine}{error.PropertyName}: {error.ErrorCode}").Trim();
        var userMessage = errors.Aggregate("",
            (e, error) => e + error.ErrorMessage + Environment.NewLine).Trim();
        return InvalidRequest<TResponse>(message, userMessage);
    }
}